package com.dao;

import com.model.MyClass;
import com.model.Student;
import utils.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class StudentDao {
    public List<Student> selectByClassName(String className) {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;

        try {
            if (className == null || className.isEmpty()) {
                return null;
            }
            connection = DBUtil.getConnection();
            String sql = "select s.id, s.name, s.sno, s.age, s.gender, s.enroll_data, s.class_id, c.id cId, c.name cName"
                    + " from student s, class c where s.class_id = c.id and c.name = ?";
            statement = connection.prepareStatement(sql);
            statement.setString(1, className);
            resultSet = statement.executeQuery();
            List<Student> list = null;

            while (resultSet.next()) {
                long id = resultSet.getLong("id");
                String name = resultSet.getString("name");
                String sno = resultSet.getString("sno");
                int age = resultSet.getInt("age");
                byte gender = resultSet.getByte("gender");
                String enroll_data = resultSet.getString("enroll_data");
                long class_id = resultSet.getLong("class_id");
                long cId = resultSet.getLong("cId");
                String cName = resultSet.getString("cName");

                Student stu = new Student();
                stu.setId(id);
                stu.setName(name);
                stu.setSno(sno);
                stu.setAge(age);
                stu.setGender(gender);
                stu.setEnrollData(enroll_data);
                stu.setClassId(class_id);

                MyClass myClass = new MyClass();
                myClass.setId(cId);
                myClass.setName(cName);

                stu.setMyClass(myClass);

                if (list == null) {
                    list = new ArrayList<>();
                }
                list.add(stu);
            }
            return list;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

}
